/*
 * @Author: 洛洛
 * @Email: logod0@qq.com
 * @LastEditors: 洛洛
 * @Date: 2024年7月13日 23:50:02
 * @LastEditTime: 2024年7月13日 23:49:53
 * @Description: 主程序
 */
console.log("服务器启动中...");
const http = require('http');
const https = require('https');
const fs = require('fs');
const express = require('express');
// 引入模块
const util = require('./src/util');
const config = util.config;
const router = require('./src/router');

var app = express();
var httpServer = http.createServer(app);
var httpsServer;
try{
    const privateKey  = fs.readFileSync('./res/ssl/private.pem', 'utf8');
    const certificate = fs.readFileSync('./res/ssl/file.crt', 'utf8');
    httpsServer = https.createServer({key: privateKey, cert: certificate}, app);
    util.listenServerPort(httpsServer, config.httpsProt).then(() => {
        console.log(`Server listening at http://localhost:${config.httpsProt}`);
    });
}catch(e){
    console.log("创建https服务器失败");
}

util.listenServerPort(httpServer, config.httpProt).then(() => {
    console.log(`Server listening at http://localhost:${config.httpProt}`);
});

router(app);

// 全局异常配置
process.on('uncaughtException', (err, origin) => {
    let log = {
        id: process.stderr.fd,
        name: "未被捕获的全局异常！",
        msg: `异常源类型: ${origin}，异常消息: ${err}`,
        data: {origin, err},
        sync: true
    };
    
    console.error(log);
    if(config.uncaughtExceptionMsgList instanceof Array 
    && config.uncaughtExceptionMsgList.some(e=>{
        return -1 < err.message.indexOf(e);
    })){
        log.name = "忽略本次全局异常";
        console.error(log);
    } else {
        process.exit(process.stderr.fd);
    }
});